<?php
/**
 * Created by PhpStorm.
 * User: dreamy
 * Date: 2019-05-25
 * Time: 11:16
 */
namespace common\services;

use common\models\Tally;
use common\models\TallyArap;
use common\models\TallyAttachment;
use common\models\TallyCategory;
use common\models\TallyFuture;
use common\models\TallyRecord;
use frontend\modules\Dao\TallyRecordDao;
use Yii;
use yii\base\Exception;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

/**
 * Class TallyRecordService
 * @package common\services
 * 账单管理
 */
class TallyRecordService extends BaseService
{
    /**
     * @param $uid
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getListByUid($uid,$condition=[])
    {
        $query = self::getQuery($uid,$condition);
        $list  = $query
            ->orderBy('tally_time desc')
            ->limit(ArrayHelper::getValue($_SERVER,'API_PAGE_NUM','10'))
            ->all();
        return $list ;
    }

    /**
     * 获取符合条件的所有记录 不带分页的
     * @param array $condition
     *
     * @return array
     */
    public static function getAll($condition=[])
    {
        $query = self::getQuery(null,$condition);

        // 默认按创建时间倒叙
        $orderByStr = 'id desc';
        // 如果有筛选账单时间就按账单时间排序
        if(isset($condition['begin_date']) || isset($condition['end_date'])) {
            $orderByStr = 'tally_time desc,id desc';
        }

        $list  = $query
            ->orderBy($orderByStr)
            ->limit(10000)
            ->asArray()
            ->all();
        return $list ?: [];
    }

    /**
     * 获取某个账本下的所有记录
     * @param array $condition
     *
     * @return array|\yii\db\ActiveRecord[]
     * @desc
     */
    public static function getList($condition=[],$uid = null)
    {

        $query = self::getQuery($uid,$condition)->andFilterWhere([
            '>','amount',0
        ]);
        // 分页相关
        $count = $query->count();
        // 构造分页对象
        $pageSize = $_SERVER['PAGE_SIZE'] ?: 10 ;
        if(isset($condition['page_limie'])){
            $pageSize = $condition['page_limie'];
        }
        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $count
        ]);
        $pagination->validatePage=false;

        // 默认按创建时间倒叙
        $orderByStr = 'id desc';
        // 如果有筛选账单时间就按账单时间排序
        if(isset($condition['begin_date']) || isset($condition['end_date'])) {
            $orderByStr = 'tally_time desc,id desc';
        }

        $list = $query
            ->orderBy($orderByStr)
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();
//        $commandQuery = clone $query;
//        echo $commandQuery->createCommand()->getRawSql();
//        die;
        $list = $list ?: [];
        return [
            'data'       => $list,
            'pageInfo'   => [
                'totalCount' => intval($count) ,
                'pageSize'   => intval($pageSize)
            ]
        ];
    }

    /**
     * 统计某一时间段内的账户收支情况
     * 2021.1.15更新增加转账类型账单的收支统计
     * @param array $condition
     *
     * @return array
     * @desc
     */
    public static function countDebt(array $condition=[], $uid = null): array
    {
        $query = self::getQuery($uid,$condition);
        //统计未入账部分
        $checkMoney = (clone $query)->andFilterWhere(['=','state',TallyRecord::STATE_INVALID])->sum('amount');
        $query->andFilterWhere(['=','state',TallyRecord::STATE_VALID]); // 只统计入账部分
        // 支出
        $outMoney = (clone $query)->andFilterWhere(['=','type',TallyRecord::TYPE_OUT])->sum('amount');
        // 收入
        $inMoney = (clone $query)->andFilterWhere(['=','type',TallyRecord::TYPE_IN])->sum('amount');
        // 转账部分查询条件
        $transQuery = self::getQuery(null,$condition,false);
        // 账户ID
        $accountId = ArrayHelper::getValue($condition,'account_id','');
        if($accountId){
            $transIn = (clone $transQuery)
                ->andFilterWhere(['=','account_dst_id',$accountId])
                ->andFilterWhere(['=','type',TallyRecord::TYPE_TRANS])
                ->sum('amount');
            $transOut = (clone $transQuery)
                ->andFilterWhere(['=','account_id',$accountId])
                ->andFilterWhere(['=','type',TallyRecord::TYPE_TRANS])
                ->sum('amount');
        }else{
            // 转账金额 初始化
            $transIn = 0;
            $transOut = 0;
        }
        $transIn = $transIn ?: 0;
        $transOut = $transOut ?: 0;
        // 转账部分的转入 算做收入部分
        $retIn = ToolService::groupMathAdd([$inMoney,$transIn]);
        $retOut = ToolService::groupMathAdd([$outMoney,$transOut]);
        $retPro = ToolService::groupMathAdd([$retIn,-1*$retOut]);
        // 转账部分的转出 算作支出部分
        return [
            'in' => $retIn,
            'out' => $retOut,
            'debt' => $retPro,
            'check' => $checkMoney ?: 0,
        ];
    }



    //获取筛选的总额
    public static function getSumAmount($condition = [],$arap_id = 0){
        $query = self::getQuery(null,$condition)->andFilterWhere([
            '=','arap_id',$arap_id
        ]);
        return $query->sum('amount');
    }

    public static function getSumAmountFuture($condition = [],$future_id = 0){
        $query = self::getQuery(null,$condition)->andFilterWhere([
            '=','future_id',$future_id
        ]);
        return $query->sum('amount');
    }

    /**
     * 返回符合查询条件的query
     * 增加逻辑 账户的筛选 转入 与 转出账户 都要包含
     * @param       $uid
     * @param array $condition
     * @param bool $accountContain 是否包含账户相关的条件处理 | 统计的时候就需要自行组装账户条件
     *
     * @return \yii\db\ActiveQuery
     * @desc
     */
    public static function getQuery($uid=null,$condition=[],$accountContain=true)
    {
        $where = [];
        if($uid){
            $where = [
                'uid'   => $uid,
            ];
        }
        // 从DB获取
        $query = TallyRecord::find()
            ->select('*')
            ->where($where);
        // 账本ID
        $tallyId = ArrayHelper::getValue($condition,'tally_id','');
        if($tallyId){
            $query->andFilterWhere(['=','tally_id',$tallyId]);
        }
        //mysql字符串拼接

        $category_parent_id = ArrayHelper::getValue($condition,'category_parent_id','');
        if($category_parent_id){
            $query->andFilterWhere(['=','category_parent_id',$category_parent_id]);
        }

        $category_child_id = ArrayHelper::getValue($condition,'category_child_id','');
        if($category_child_id){
            $query->andFilterWhere(['=','category_child_id',$category_child_id]);
        }

        $category_route_like = ArrayHelper::getValue($condition,'category_route_like','');

        if($category_route_like){
            $query->andFilterWhere(['like','category_route',','.$category_route_like.',']);
        }

        // 账目类别
        $type = ArrayHelper::getValue($condition,'type','');
        if($type){
            $query->andFilterWhere(['=','type',$type]);
        }
        // 上个id
        $last_id = ArrayHelper::getValue($condition,'last_id','');
        if($last_id){
            $query->andFilterWhere(['>','id',$last_id]);
        }
        // 分类ID
        $categoryId = ArrayHelper::getValue($condition,'category_id','');
        if($categoryId){
            $query->andFilterWhere(['=','category_id',$categoryId]);
        }
        // 分类ID集合
        $categoryIds = ArrayHelper::getValue($condition,'category_ids','');
        if($categoryIds){
            $query->andFilterWhere(['in','category_id',explode(',',$categoryIds)]);
        }
        if($accountContain) {
            // 账户ID
            $accountId = ArrayHelper::getValue($condition,'account_id','');
            if($accountId){
//            $query->andFilterWhere(['=','account_id',$accountId]);
                $query->andFilterWhere(['or',
                        ['account_id' => $accountId],
                        ['account_dst_id' => $accountId],
                    ]
                );
            }
            // 账户ID集合
            $accountIds = ArrayHelper::getValue($condition,'account_ids','');
            if($accountIds){
//            $query->andFilterWhere(['in','account_id',explode(',',$accountIds)]);
                $query->andFilterWhere(['or',
                        ['in','account_id', explode(',',$accountIds) ],
                        ['in','account_dst_id',explode(',',$accountIds)],
                    ]
                );
            }
        }

        $accounts = ArrayHelper::getValue($condition,'accounts','');
        if($accounts){
            $query->andFilterWhere(['or',
                    ['in','account_id', $accounts ],
                    ['in','account_dst_id',$accounts],
                ]
            );
        }






//        print_r($query->createCommand()->rawSql);
//        die;
        // 商家ID
        $storeId = ArrayHelper::getValue($condition,'store_id','');
        if($storeId){
            $query->andFilterWhere(['=','store_id',$storeId]);
        }
        // 商家ID集合
        $storeIds = ArrayHelper::getValue($condition,'store_ids','');
        if($storeIds){
            $query->andFilterWhere(['in','store_id',explode(',',$storeIds)]);
        }


        $stores = ArrayHelper::getValue($condition,'stores','');
        if($stores){
            $query->andFilterWhere(['in','store_id',$stores]);
        }
        // 项目ID
        $projectId = ArrayHelper::getValue($condition,'project_id','');
        if($projectId){
            $query->andFilterWhere(['=','project_id',$projectId]);
        }
        // 项目ID集合
        $projectIds = ArrayHelper::getValue($condition,'project_ids','');
        if($projectIds){
            $query->andFilterWhere(['in','project_id',explode(',',$projectIds)]);
        }


        $projects = ArrayHelper::getValue($condition,'projects','');
        if($projects){
            $query->andFilterWhere(['in','project_id',$projects]);
        }
        // 成员ID
        $memberId = ArrayHelper::getValue($condition,'member_id','');
        if($memberId){
            $query->andFilterWhere(['=','member_id',$memberId]);
        }
        // 成员ID集合
        $memberIds = ArrayHelper::getValue($condition,'member_ids','');
        if($memberIds){
            $query->andFilterWhere(['in','member_id',explode(',',$memberIds)]);
        }


        $members = ArrayHelper::getValue($condition,'members','');
        if($members){
            $query->andFilterWhere(['in','member_id',$members]);
        }

        // 设置默认空 方便下面做判断
        if(!isset($condition['begin_date'])) $condition['begin_date'] = '';
        if(!isset($condition['end_date'])) $condition['end_date'] = '';

        // 时间段查询 包含右时间边界
        if($condition['begin_date'] != '' && $condition['end_date'] != '') {
            $condition['end_date'] = $condition['end_date'].' : 23:59:59';
            $query->andFilterWhere(['between','tally_time',$condition['begin_date'], $condition['end_date']]);
        }
        if($condition['begin_date'] != '' && $condition['end_date'] == '') {
            $query->andFilterWhere(['>','tally_time',$condition['begin_date']]);
        }
        if($condition['begin_date'] == '' && $condition['end_date'] != '') {
            $condition['end_date'] = date('Y-m-d',strtotime('+1 day',strtotime($condition['end_date'])));
            $query->andFilterWhere(['<','tally_time',$condition['end_date']]);
        }

//        print_r($query->createCommand()->rawSql);
//        die;
        // 备注关键词
        $memo = ArrayHelper::getValue($condition,'memo','');
        if($memo){
            $query->andFilterWhere(['like','memo',$memo]);
        }
        // 包含状态
        $state = ArrayHelper::getValue($condition,'state');
        if($state !== null){
            $query->andFilterWhere(['=','state',$state]);
        }
        return $query;
    }

    /**
     * @param $formData
     * @return bool
     */
    public static function create($formData)
    {
        $model = new TallyRecord();
        $model->load($formData,'');
        $model->state = $formData['state'];
        if(isset($formData['is_refund'])){
            $model->is_refund = $formData['is_refund'];
        }
        $beforeCheck = self::formatFieldBeforeSave($model,$formData);
        if(!$beforeCheck) {
            return false; // 前置数据检查异常 返回错误
        }
        if ($model->validate() && $model->save()) {
            // 处理附件增加
            self::insertAttachment($formData,$model->id);
            return $model->id;
        }else{
            Yii::error('Tally Record insert error:'.current($model->getFirstErrors()).';post:'.Json::encode($formData,JSON_UNESCAPED_UNICODE));
            self::setError(current($model->getFirstErrors()));
            return false;
        }
    }

    /**
     * @desc 数据更新之前的前置操作 一些冗余字段的处理
     * @param $model
     * @return mixed
     */
    public static function formatFieldBeforeSave(&$model,$formData = [])
    {


//        print_r();exit;
        // 挂账类型重写类别
        if(TallyRecordDao::checkIsHasField($formData,'is_gua') && $formData['is_gua'] == 1) {
//            $model->category_pid = TallyCategory::GZ_PID;
            $model->category_name = TallyCategoryService::getTitleGlobal($model->category_id);
            $model->category_pid    = TallyCategoryService::getPidGlobal($model->category_id);
            $model->category_pname = TallyCategoryService::getTitleGlobal($model->category_pid);
            $model->category_ppid    = TallyCategoryService::getPidGlobal($model->category_pid);
            $model->category_ppname = TallyCategoryService::getTitleGlobal($model->category_ppid);
            $model->category_parent_id = ($model->category_ppid == 0 ? $model->category_pid : $model->category_ppid);
            $model->category_child_id = ($model->category_ppid == 0 ? $model->category_id : $model->category_pid);
            $model->category_route = ','.$model->category_ppid.','.$model->category_pid.','.$model->category_id.',';
            // 如果存在arap_id 检查金额不能超出
            if($model->arap_id) {
                $arapInfo = TallyArap::find()->where(['id'=>$model->arap_id])->asArray()->one();
                if(!$arapInfo) {
                    self::setError('挂账记录查找失败！该账单为异常账单请手动删除！');
                    return false ;
                }
                // 重新统计已有金额
                $alreadyAmount = TallyRecord::find()->where([
                    'arap_id' => $model->arap_id,
                    'state' => TallyRecord::STATE_VALID
                ])->andWhere(['<>','id',$model->id])->sum('amount');
                $maxMoney = ToolService::groupMathAdd([$arapInfo['amount'],-1*$alreadyAmount]);
                if($model->amount > $maxMoney) {
                    self::setError('账单金额超出挂账记录最大可核销金额：'.$maxMoney);
                    return false ;
                }
            }
        }else{
            // 非转账类型 才考虑分类
            if($model->type != $model::TYPE_TRANS) {
                // 获取分类名称
                $category_name = TallyCategoryService::getTitleGlobal($model->category_id);
                if(is_null($category_name)) {
                    self::setError('分类名称转换失败|请重新选择分类');
                    return false ;
                }
                $model->category_name = $category_name ;


                // 一级分类缓存数据
                $category_pid    = TallyCategoryService::getPidGlobal($model->category_id);
                if(!$category_pid) {
                    self::setError('请在二级分类建立账单');
                    return false ;
                }else{
                    $model->category_pid = $category_pid ;
                }
                $category_pname  = TallyCategoryService::getTitleGlobal($category_pid);
                $model->category_ppid    = TallyCategoryService::getPidGlobal($model->category_pid);
                $model->category_ppname = TallyCategoryService::getTitleGlobal($model->category_ppid);
                $model->category_pname = $category_pname ;
                $model->category_parent_id = $model->category_ppid == 0 ? $category_pid : $model->category_ppid;
                $model->category_child_id = $model->category_ppid == 0 ? $model->category_id : $model->category_pid;
                $model->category_route = ','.$model->category_ppid.','.$model->category_pid.','.$model->category_id.',';

            }
        }
        // amount金额不能小于0
        if($model->amount <= 0) {
            self::setError('账单金额必须大于0');
            return false ;
        }
        // 获取账户名称
        $account_name = TallyAccountService::getTitleGlobal($model->account_id);
        if(is_null($account_name)) {
            self::setError('账户名称转换失败|请重新选择账户');
            return false ;
        }
        if($model->account_dst_id){
            $account_dst_name = TallyAccountService::getTitleGlobal($model->account_dst_id);
            $model->account_dst_name = $account_dst_name ;
        }
        $model->account_name = $account_name ;
        // 获取商家名称
        if($model->store_id) {
            $store_name = TallyStoreService::getTitleById($model->store_id);
            $model->store_name = $store_name ?: '';
        }else{
            $model->store_id = 0 ;
            $model->store_name = '' ;
        }
        // 获取项目情况
        if($model->project_id) {
            $project_name = TallyProjectService::getTitleById($model->project_id);
            $model->project_name = $project_name ?: '';
        }else{
            $model->project_id = 0 ;
            $model->project_name = '' ;
        }
        // 获取商户情况
        if($model->member_id) {
            $member_name = TallyMemberService::getTitleById($model->member_id);
            $model->member_name = $member_name ?: '';
        }else{
            $model->member_id = 0 ;
            $model->member_name = '' ;
        }



        $model->future_id = $formData['future_id'];
        return $model;
    }

    /**
     * @param $formData
     * @param $recId
     * @return bool
     * @notes 增加附件表
     */
    public static function insertAttachment($formData,$recId)
    {
        $attachS = explode(',', ArrayHelper::getValue($formData,'attachment',''));
        $attachS = array_filter($attachS);
        if(!empty($attachS)) {
            $data = [
                'tally_id'          => ArrayHelper::getValue($formData,'tally_id'),
                'tally_record_id'   => $recId,
                'uid'               => ArrayHelper::getValue($formData,'uid'),
            ];
            foreach ($attachS as $attach) {
                if(!$attach) continue;
                $data['file_name'] = $attach;
                $model = new TallyAttachment();
                $model->load($data,'');
                $model->save();
            }
        }
        return true;
    }

    /**
     * @notes 附件数据清理
     * @param $formData
     * @param $recId
     * @return bool
     */
    public static function deleteAttachment($formData,$recId)
    {
        $data = [
            'tally_id'          => ArrayHelper::getValue($formData,'tally_id'),
            'tally_record_id'   => $recId,
            'uid'               => ArrayHelper::getValue($formData,'uid'),
        ];
        TallyAttachment::deleteAll($data);
        return true;
    }

    /**
     * 处理账单入库后或者审核通过后的 账户金额关系
     * @param $form
     * @param $reverse boolean 是否为逆向操作
     *
     * @return bool
     * @throws \yii\base\Exception
     * @desc
     */
    public static function calRelationAmount($form,$reverse=false)
    {
        // 不同类型的进行事务更新账户金额
        $upAccountWhere = [
            'id'  => $form->account_id,
        ];
        $amount = $form->amount;
        if($form->type == TallyRecord::TYPE_IN) {
            $optMoney = !$reverse ? abs($amount) : -1*abs($amount); //如果是逆向操作要反着来
            // 收入 账户金额增加
            $upRes = TallyAccountService::updateMoney($upAccountWhere,$optMoney);
            $upState = $upRes!==false;
        }else if($form->type == TallyRecord::TYPE_OUT) {
            $optMoney = !$reverse ? -1*abs($amount) : abs($amount); //如果是逆向操作要反着来
            // 支出 账户金额减少
            $upRes = TallyAccountService::updateMoney($upAccountWhere,$optMoney);
            $upState = $upRes!==false;
        }else if($form->type == TallyRecord::TYPE_TRANS) {
            $optMoney = !$reverse ? -1*abs($amount) : abs($amount);
            // 转账 账户金额增加&减少
            $upState1 = TallyAccountService::updateMoney($upAccountWhere,$optMoney);
            $upAccountWhere['id'] = $form->account_dst_id;
            $upState2 = TallyAccountService::updateMoney($upAccountWhere,-1*$optMoney);
            $upState  = $upState1 && $upState2;
        }
        if(!$upState) {
            throw new Exception(TallyAccountService::getError());
        }
        return true ;
    }

    /**
     * @param $condition
     * @param $formData
     * @throws
     * @return bool
     */
    public static function update($condition,$formData)
    {
        $model = TallyRecord::find()->where($condition)->one();
        if(!$model){
            self::setError('账本不存在');
            return false ;
        }
        $oldModel = clone $model;
        // 修改之前的类型 金额 先逆向回去 再进行重新计算
        /*$oldType = $model->type;
        $oldMoney = $model->amount;
        $oldAccount = $model->account_id;
        $oldAccountDst = $model->account_dst_id;*/
        // 本次修改的类型 金额
        /*$newType = $formData['type'];
        $newMoney = $formData['amount'];
        $newAccount = $formData['account_id'];
        $newAccountDst = $formData['account_dst_id'];*/
        $model->load($formData,'');
        $formData['tally_id'] = $model->tally_id;
        $model =  self::formatFieldBeforeSave($model);
        if(!$model) {
            return false; // 前置数据检查异常 返回错误
        }
        if ($model->validate() && $model->save()) {
            // 附件先全部清除掉
            self::deleteAttachment($formData,$model->id);
            // 处理附件增加
            self::insertAttachment($formData,$model->id);
            // 只针对状态正常的订单进行更新调整
            if($model->state == TallyRecord::STATE_VALID){
                // 处理金额变动差异 先对账户进行逆向操作 然后再进行正向处理
                self::calRelationAmount($oldModel,true);
                self::calRelationAmount($model);
                // 如果涉及挂账操作 进行挂账金额重新核算
                if($model->arap_id) {
                    TallyArapService::calRelationAmount($model->arap_id);
                }
            }else if($model->state == TallyRecord::STATE_INVALID && $oldModel->state == TallyRecord::STATE_VALID){
                self::calRelationAmount($oldModel,true); //只进行逆向然后进入审核状态
                // 如果涉及挂账操作 进行挂账金额重新核算
                if($model->arap_id) {
                    TallyArapService::calRelationAmount($model->arap_id);
                }
            }
            return true ;
        }else{
            Yii::error('Tally update error:'.current($model->getFirstErrors()).';post:'.Json::encode($formData,JSON_UNESCAPED_UNICODE));
            self::setError(current($model->getFirstErrors()));
            return false;
        }
    }

    /**
     * @param $condition
     * @return bool
     * @throws
     */
    public static function delete($condition): bool
    {
        $uid = ArrayHelper::getValue($condition,'uid');//操作者的UID
        unset($condition['uid']);
        $model = TallyRecord::find()->where($condition)->one();
        if(!$model){
            self::setError('账单记录不存在');
            return false ;
        }


        $futureInfo = TallyFuture::find()->where([
            'tally_record_id' => $condition['id']
        ])->one();

        if($futureInfo){
            self::setError('母单不允许删除!');
            return false ;
        }
        if($model['future_id'] != 0){
            $futureInfo = TallyFuture::find()->where([
                'id' => $model['future_id']
            ])->one();
            if($futureInfo['state'] == 3){
                self::setError('冲销完成禁止删除流水');
                return false ;
            }
        }


        // 是否有权限进行删除操作
        if($model->uid == $uid){
            $canDel = true ; // 是本人创建的当然可以删除
        }else{
            // 该用户是否可删除账套下的账单 tallyId的角色关系
            $canDel =  TallyPmService::checkPermission($uid,$model->tally_id,'delete');
        }
        if(!$canDel){
            self::setError('不具备删除权限');
            return false ;
        }
        $oldModel = clone $model;
        if ($model->delete()) {
            if($model->future_id == 0 || $model->is_refund == 1){
                self::calRelationAmount($oldModel,true);
            }
            // 如果涉及挂账操作 进行挂账金额重新核算
            if($model->arap_id) {
                TallyArapService::calRelationAmount($model->arap_id);
            }
            // 涉及进销存 库存逆向
            if($model->stock_id) {
                TallyStockRecordService::handleProductFlow($model->stock_id,$model->id,true);
            }
            //核销记录==>逆向回滚余额
            if($model->future_id != 0){
                $future_id = $model['future_id'];
                $futureInfo = TallyFuture::find()->where([
                    'id' => $future_id
                ])->one();
                $totalAmount = ToolService::moneyFormat($futureInfo->amount);
                $alreadyAmount = TallyRecord::find()->where([
                    'future_id' => $future_id,
                ])->andFilterWhere(['<>','future_id',$futureInfo['tally_record_id']])->sum('amount');
                $alreadyAmount = $alreadyAmount ?: 0;
                $remainAmount = ToolService::groupMathAdd([$totalAmount,-1*$alreadyAmount]);
                $futureInfo->amount_remain = $remainAmount;
                if($totalAmount == $remainAmount ){
                    $futureInfo->state = TallyArap::STATE_VALID;
                }else if($remainAmount > 0) {
                    $futureInfo->state = TallyArap::STATE_ARAP_ING;
                }else if($remainAmount == 0) {
                    $futureInfo->state = TallyArap::STATE_ARAP_OVER;
                }
                $futureInfo->save();
                $old_tall_record_info = TallyRecord::find()->where([
                    'id' => $futureInfo['tally_record_id']
                ])->one();

                $old_tall_record_info->amount =$remainAmount;

                $old_tall_record_info->save();
            }
            return true ;
        }else{
            self::setError(current($model->getFirstErrors()));
            return false;
        }
    }
}
